/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, { memo, useCallback, useMemo } from 'react';
import { StyleSheet, ViewProps } from 'react-native';
import { TapGestureHandler } from 'react-native-gesture-handler';
import Animated, { useAnimatedGestureHandler, runOnJS } from 'react-native-reanimated';
import type { TapGestureHandlerGestureEvent } from 'react-native-gesture-handler';

export interface AdaptiveSideSheetBackdropProps {
  animatedIndex: Animated.SharedValue<number>;

  animatedPosition: Animated.SharedValue<number>;

  style?: ViewProps['style'];

  onPress?: () => void;

  enablePressToDismiss?: boolean;

  opacity?: number;
}

const AdaptiveSideSheetBackdropComponent = ({
  animatedIndex,
  animatedPosition,
  style,
  onPress,
  enablePressToDismiss = true,
  opacity = 0.64,
}: AdaptiveSideSheetBackdropProps): JSX.Element => {
  const handleOnPress = useCallback(() => {
    if (enablePressToDismiss && onPress) {
      onPress();
    }
  }, [enablePressToDismiss, onPress]);

  const gestureHandler = useAnimatedGestureHandler<TapGestureHandlerGestureEvent>(
    {
      onFinish: () => {
        runOnJS(handleOnPress)();
      },
    },
    [handleOnPress],
  );

  const containerStyle = useMemo(() => [styles.container, style], [style]);

  const AnimatedView = <Animated.View style={containerStyle} />;

  return enablePressToDismiss ? <TapGestureHandler onGestureEvent={gestureHandler}>{AnimatedView}</TapGestureHandler> : AnimatedView;
};

const styles = StyleSheet.create({
  container: {
    bottom: 0,
    left: 0,
    position: 'absolute',
    right: 0,
    top: 0,
  },
});

const AdaptiveSideSheetBackdrop = memo(AdaptiveSideSheetBackdropComponent);
AdaptiveSideSheetBackdrop.displayName = 'AdaptiveSideSheetBackdrop';

export default AdaptiveSideSheetBackdrop;
